import {Http, Headers} from "@angular/http";
import {Injectable} from "@angular/core";
/**
 * Created by jackbranson on 2017/4/6.
 */

@Injectable()
export class AppHttpService
{
  constructor(private http: Http)
  {

  }

  private prepare(data: Object, header: Object)
  {
    let headers = new Headers();
    for (let name in header)
    {
      headers.set(name, header[name]);
    }
    headers.set('Content-Type', 'application/json');
    let data_str = JSON.stringify(data);
    return {data: data_str, headers: {headers: headers}};
  }

  get(url: string, header: Object = {})
  {
    let obj = this.prepare({}, header);
    return this.http.get(url, obj.headers);
  }

  post(url: string, data: Object, header: Object = {})
  {
    let obj = this.prepare(data, header);
    return this.http.post(url, obj.data, obj.headers);
  }

  post_form_data(url: string, data: Object, header: Object = {})
  {
    let headers = new Headers();
    for (let name in header)
    {
      headers.set(name, header[name]);
    }
    headers.set('Content-Type', 'multipart/form-data');
    return this.http.post(url, data, {headers: headers});
  }

  put(url: string, data: Object, header: Object = {})
  {
    let obj = this.prepare(data, header);
    return this.http.put(url, obj.data, obj.headers);
  }

  delete(url: string, header: Object = {})
  {
    let obj = this.prepare({}, header);
    return this.http.delete(url, obj.headers);
  }

  patch(url: string, data: Object, header: Object = {})
  {
    let obj = this.prepare(data, header);
    return this.http.patch(url, obj.data, obj.headers);
  }

  head(url: string, header: Object = {})
  {
    let obj = this.prepare({}, header);
    return this.http.head(url, obj.headers);
  }

  options(url: string, header: Object = {})
  {
    let obj = this.prepare({}, header);
    return this.http.options(url, obj.headers);
  }
}
